package com.adams.security.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang.time.StopWatch;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.adams.access.db.bean.User;

public class UserDetailDaoImpl implements UserDetailsService,InitializingBean  {

//	private Logger logger = Logger.getLogger(HibernateEmployeeDao.class);
	private HibernateTemplate hibernateTemplate;
 
	/* (non-Javadoc)
	 * @see org.acegisecurity.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public UserDetails loadUserByUsername(final String username)
			throws UsernameNotFoundException, DataAccessException {
//		logger.info("Getting User ID:"+username);
		StopWatch watch = new StopWatch();
		watch.start();
		try { 
			List users = getHibernateTemplate().executeFind(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Criteria c = session.createCriteria(User.class);
					c.add(Restrictions.eq("userName", username).ignoreCase());
//					Criteria c2 = c.createCriteria("role");
//					c.add(Restrictions.eq("password", username).ignoreCase());
//					c.add(Restrictions.isNull("terminDate"));
//					c.setFetchMode("impersonationEmployees", FetchMode.JOIN);
//					c.setFetchMode("preferences", FetchMode.JOIN);
//					c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
					return c.list(); 
			}}); 
			
//			logger.info("Got "+employees.size()+" Matches for User ID:"+username);
			if(users.size() > 0) {
				 GrantedAuthority[] auths=new GrantedAuthority[1];
//				 GrantedAuthorityImpl auth2=new GrantedAuthorityImpl("ROLE_ADMIN");
				 auths[0]=new GrantedAuthorityImpl("ROLE_USER");
					VASUser user = new VASUser(((User)users.get(0)).getUserName(),((User)users.get(0)).getPassword(), true, true, true, true, auths,((User)users.get(0))); 
//				
					return  user;
			} else {
				throw new UsernameNotFoundException("User "+ username +" Not found in VAS");
			}
		} finally {
			watch.stop();
//			logger.debug("Login took "+watch.getTime()+" ms");
		}
	}
 
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
	}
  
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
}
